﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XChip_Common
{
    /// <summary>
    /// 原码与补码的转换
    /// </summary>
    public class OCCHelper
    {
        /// <summary>
        /// 求一个16位数数的补码
        /// </summary>
        /// <param name="OriginalCode">传入一个Int16整型</param>
        /// <returns></returns>
        public static int ConvertComplementCode(int OriginalCode)
        {
            int a = short.MaxValue;
            int b = short.MinValue;
            int c = a - b;
            int d = 0;
            if (OriginalCode > 0)
            {
                d = -(c - OriginalCode + 1);
            }
            else
            {
                d = c + OriginalCode + 1;
            }
            return d;
        }

      
        /// <summary>
        /// 求一个32位数的补码
        /// </summary>
        /// <param name="OriginalCode">传入一个Int32整型</param>
        /// <returns></returns>
        public static long ConvertComplementCode(long OriginalCode)
        {
            long a = int.MaxValue;
            long b = int.MinValue;
            long c = a - b;
            long d = 0;
            if (OriginalCode > 0)
            {
                d = -(c - OriginalCode + 1);
            }
            else
            {
                d = c + OriginalCode + 1;
            }
            return d;
        }


        /// <summary>
        /// 补高两位转成int类型
        /// </summary>
        /// <param name="OCode">16进制字符</param>
        /// <param name="bit">默认值8 </param>
        /// <returns></returns>
        public static int ConvertBinaryCode(string OCode) {
            var temp16 = Convert.ToUInt32(OCode, 16);
            var bit = OCode.Length * 4;
            var temp2 = System.Convert.ToString(temp16, 2).PadLeft(bit, '0');
            //高位换成11
            var tp2 = temp2.ToCharArray();
            tp2[0] = '1';
            tp2[1] = '1';
            return System.Convert.ToInt32(new string(tp2), 2);
        }
    }
}
